<?php


namespace App\backend\services;


use App\backend\models\CategoryModel;
use App\backend\models\GoodsCronTimeModel;
use App\backend\models\GoodsGroupModel;
use App\backend\models\GoodsKeywordModel;
use App\backend\models\GoodsModel;
use App\backend\models\GoodsQuotaModel;
use App\backend\models\GoodsTagModel;
use App\backend\models\GoodSupportModel;
use App\common\services\BaseServices;
use App\Exceptions\InvalidRequestException;

class GoodsServices extends BaseServices
{

    public $logFile = 'GoodsServices';

    public function __construct()
    {

    }

    /**
     * 获取 - 商品列表
     *
     * @param $data //请求参数数组
     * @return array
     */
    public static function getGoodsList($data)
    {
        $page = !isset($data['page']) ? 1 : $data['page'];unset($data['page']);
        $limit = !isset($data['limit']) ? 10 : $data['limit'];unset($data['limit']);

        $where_data = [];
        if (isset($data['title']) && !empty($data['title'])) {
            $where_data[] = ['goods.title','like',"%{$data['title']}%"];
        }
        if (isset($data['type']) && !empty($data['type'])) {
            $where_data[] = ['goods.type','=',$data['type']];
        }
        if (isset($data['categorys']) && !empty($data['categorys'])) {
            $where_data[] = ['goods.categorys','=',$data['categorys']];
        }
        if (isset($data['group']) && !empty($data['group'])) {
            $where_data[] = ['goods.group','=',$data['group']];
        }
        if (isset($data['is_support']) && !empty($data['is_support'])) {
            $where_data[] = ['goods.is_support','=',$data['is_support']];
        }
        if (isset($data['sales_group']) && !empty($data['sales_group'])) {
            $sales_group = explode(',', $data['sales_group']);
            $where_data[] = ['goods.real_sales', '>=', $sales_group[0]];
            $where_data[] = ['goods.real_sales', '<=', $sales_group[1]];
        }
        if (isset($data['price_group']) && !empty($data['price_group'])) {
            $price_group = explode(',', $data['price_group']);
            $where_data[] = ['goods.price', '>=', $price_group[0]];
            $where_data[] = ['goods.price', '<=', $price_group[1]];
        }
        if (isset($data['city_id']) && !empty($data['city_id'])) {
            $where_data[] = ['goods.city_id','=',$data['city_id']];
        }
        if (isset($data['status']) && !empty($data['status'])) {
            $where_data[] = ['goods.status','=',$data['status']];
        }

        $select = [
            'goods.id', 'goods.display_order', 'goods.title', 'goods.thumb', 'goods.type', 'goods.price',
            'goods.show_sales', 'goods.stock', 'goods.city_id', 'goods.store_id', 'goods.created_at', 'goods.status',
            'goods.province', 'goods.city', 'goods.region', 'store.store_name'
        ];
        $list = GoodsModel::left_join_listed($page, $limit, $where_data, [], $select);
        if (empty($list)) {
            throw new InvalidRequestException(10009);
        }

        foreach ($list as $value) {
            if (is_array($value) && !empty($value)) {
                foreach ($value as $v) {
                    $v->created_at = date('Y-m-d H:i:s', $v->created_at);
                }
            }
        }

        return $list;
    }

    /**
     * 添加/编辑 - 商品 基础信息
     *
     * @param $data //请求参数数组
     * @return array
     */
    public static function modifyBaseGoods($data)
    {
        if (empty($data) && $data == false) {
            throw new InvalidRequestException(10009);
        }

        $ids['id'] = !empty($data['goods_id']) ? $data['goods_id'] : 0;unset($data['goods_id']);

        $where_data = [];
        if (isset($ids['id']) && !empty($ids['id'])) {
            $data['updated_at'] = time();
            $updated_id = GoodsModel::updatedData($ids, $data);
            if ($updated_id) {
                $where_data[] = ['id', '=', $ids['id']];

                $res = json_encode($data, JSON_UNESCAPED_UNICODE);
                admin_operation_log(101, "ID:{$ids['id']} DATA:{$res}");
            }
        } else {
            $data['created_at'] = time();
            $insert_id = GoodsModel::insertGetIdData($data);
            if ($insert_id) {
                $where_data[] = ['id', '=', $insert_id];

                $res = json_encode($data, JSON_UNESCAPED_UNICODE);
                admin_operation_log(100, "ID:{$ids['id']} DATA:{$res}");
            }
        }

        $select = [
            'id', 'type', 'title', 'subtitle', 'title_tag', 'thumb_url',
            'video_url', 'thumb', 'keywords', 'categorys', 'group', 'is_support',
            'province', 'city', 'region', 'short_title', 'tag_ids'
        ];
        $list = GoodsModel::info($where_data, $select);
        if (empty($list)) {
            throw new InvalidRequestException(10009);
        }

        // 商品轮播图
        if (!empty($list->thumb_url)) {
            $list->thumb_url = get_string_array($list->thumb_url);
        }
        // 关键词
        if (!empty($list->keywords)) {
            $list->keywords = GoodsKeywordModel::in_arr($list->keywords);
        }
        // 商品分类
        if (!empty($list->categorys)) {
            $list->categorys = CategoryModel::in_arr($list->categorys);
        }
        // 商品分组
        if (!empty($list->group)) {
            $list->group = GoodsGroupModel::in_arr($list->group);
        }
        // 商品支持
        if (!empty($list->is_support)) {
            $list->is_support = GoodSupportModel::in_arr($list->is_support);
        }
        // 商品特征标签
        if (!empty($list->tag_ids)) {
            $list->tag_ids = GoodsTagModel::in_arr($list->tag_ids);
        }

        return $list;
    }

    /**
     * 添加/编辑 - 商品 价格/库存
     *
     * @param $data //请求参数数组
     * @return array
     */
    public static function modifyPriceStockGoods($data)
    {
        if (empty($data) && $data == false) {
            throw new InvalidRequestException(10009);
        }

        $ids['id'] = !empty($data['goods_id']) ? $data['goods_id'] : 0;unset($data['goods_id']);

        $where_data[] = ['id', '=', $ids['id']];
        $data['updated_at'] = time();
        $update_state = GoodsModel::updatedData($ids, $data);
        if (empty($update_state)) {
            throw new InvalidRequestException(30003);
        }

        $select = [
            'id', 'price', 'cost_price', 'stock', 'stock_forewarn', 'show_sales',
            'detail_show_stock_status', 'detail_show_sales_status'
        ];
        $list = GoodsModel::info($where_data, $select);
        if (empty($list)) {
            throw new InvalidRequestException(10009);
        }

        return $list;
    }

    /**
     * 添加/编辑 - 商品 附加规格
     *
     * @param $data //请求参数数组
     * @return array
     */
    public static function modifySkuInfoGoods($data)
    {
        if (empty($data) && $data == false) {
            throw new InvalidRequestException(10009);
        }

        $ids['id'] = !empty($data['goods_id']) ? $data['goods_id'] : 0;unset($data['goods_id']);
        $where_data[] = ['id', '=', $ids['id']];
        $data['updated_at'] = time();
        $update_state = GoodsModel::updatedData($ids, $data);
        if (empty($update_state)) {
            throw new InvalidRequestException(30003);
        }

        $select = ['id', 'sku_id', 'is_sku', 'default_sku_id'];
        $list = GoodsModel::info($where_data, $select);
        if (empty($list)) {
            throw new InvalidRequestException(10009);
        }

        return $list;
    }

    /**
     * 添加/编辑 - 商品 物流设置
     *
     * @param $data //请求参数数组
     * @return array
     */
    public static function modifyLogisticsGoods($data)
    {
        if (empty($data) && $data == false) {
            throw new InvalidRequestException(10003);
        }

        if (empty($data['fare']) && empty($data['fare_model'])) {
            throw new InvalidRequestException(30002);
        }

        $ids['id'] = !empty($data['goods_id']) ? $data['goods_id'] : 0;unset($data['goods_id']);

        $where_data[] = ['id', '=', $ids['id']];
        $data['updated_at'] = time();
        $update_state = GoodsModel::updatedData($ids, $data);
        if (empty($update_state)) {
            throw new InvalidRequestException(30003);
        }

        $select = ['id', 'is_logistics', 'self_pickup_point', 'fare', 'fare_model', 'weight', 'volume'];
        $list = GoodsModel::info($where_data, $select);
        if (empty($list)) {
            throw new InvalidRequestException(10009);
        }

        return $list;
    }

    /**
     * 添加/编辑 - 商品 详情
     *
     * @param $data //请求参数数组
     * @return array
     */
    public static function modifyDescriptionGoods($data)
    {
        if (empty($data) && $data == false) {
            throw new InvalidRequestException(10009);
        }

        $ids['id'] = !empty($data['goods_id']) ? $data['goods_id'] : 0;unset($data['goods_id']);
        $where_data[] = ['id', '=', $ids['id']];
        $data['updated_at'] = time();
        $update_state = GoodsModel::updatedData($ids, $data);
        if (empty($update_state)) {
            throw new InvalidRequestException(30003);
        }

        $select = ['id', 'params_name', 'params_type', 'params_content'];
        $list = GoodsModel::info($where_data, $select);
        return $list;
    }

    /**
     * 添加/编辑 - 商品 状态
     *
     * @param $data //请求参数数组
     * @return array
     */
    public static function modifyStateGoods($data)
    {
        if (empty($data) && $data == false) {
            throw new InvalidRequestException(10009);
        }

        if (!isset($data['goods_id']) && empty($data['goods_id'])) {
            throw new InvalidRequestException(30000);
        }

        $status = !empty($data['status']) ? $data['status'] : 0;unset($data['status']);
        if ($status == 9 && (!isset($data['listing_time']) || empty($data['listing_time']))) {
            throw new InvalidRequestException(30004);
        }

        if (isset($data['off_shelf_time']) && empty($data['off_shelf_time'])) {
            throw new InvalidRequestException(30005);
        }


        GoodsModel::updatedData(['id' => $data['goods_id']], ['status' => $status]);
        $where_data[] = ['goods_id', '=', $data['goods_id']];
        $data['listing_time'] = isset($data['listing_time']) ? strtotime($data['listing_time']) : 0;
        $data['off_shelf_time'] = isset($data['off_shelf_time']) ? strtotime($data['off_shelf_time']) : 0;
        $data['setting_type'] = 1;
        $getOne = GoodsCronTimeModel::info($where_data, ['id']);
        if (empty($getOne)) {
            $update_state = GoodsCronTimeModel::insertData($data);
        } else {
            unset($data['goods_id']);
            $update_state = GoodsCronTimeModel::updatedData($where_data, $data);;
        }

        if (empty($update_state)) {
            throw new InvalidRequestException(30003);
        }

        $select_data = ['listing_time', 'off_shelf_time'];
        $list = GoodsCronTimeModel::info($where_data, $select_data);
        $list = object_to_array($list);
        if (empty($list)) {
            throw new InvalidRequestException(10009);
        }
        $list['status'] = $status;
        $list['listing_time'] = $list['listing_time'] != 0 ? date('Y-m-d H:i:s', $list['listing_time']) : '';
        $list['off_shelf_time'] = $list['off_shelf_time'] != 0 ? date('Y-m-d H:i:s', $list['off_shelf_time']) : '';
        return $list;
    }

    /**
     * 添加/编辑 - 商品 限购
     *
     * @param $data //请求参数数组
     * @return array
     */
    public function modifyQuotaGoods($data)
    {
        if (empty($data) && $data == false) {
            $this->logError('参数传递错误', ['data' => $data]);
            throw new InvalidRequestException(10009);
        }

        if (!isset($data['goods_id']) && empty($data['goods_id'])) {
            throw new InvalidRequestException(30000);
        }

        $where_data[] = ['goods_id', '=', $data['goods_id']];
        $getOne = GoodsQuotaModel::info($where_data, ['id']);
        if (empty($getOne)) {
            $update_state = GoodsQuotaModel::insertData($data);
        } else {
            unset($data['goods_id']);
            $update_state = GoodsQuotaModel::updatedData($where_data, $data);;
        }

        if (empty($update_state)) {
            throw new InvalidRequestException(30003);
        }

        $select = [
            'quota_status', 'forerver_quota_status', 'cycle_quota_status',
            'cycle', 'customize_day', 'customize_piece', 'browse_right_status'
        ];
        $list = GoodsQuotaModel::info($where_data, $select);
        if (empty($list)) {
            throw new InvalidRequestException(10009);
        }

        return $list;
    }

    /**
     * 删除/下架 - 商品
     *
     * @param $data //请求参数数组
     * @return array
     */
    public static function updateGoodStatus($data)
    {
        if (empty($data) && $data == false) {
            throw new InvalidRequestException(10009);
        }

        $data['id'] = !empty($data['goods_id']) ? $data['goods_id'] : 0;unset($data['goods_id']);
        $update_data['status'] = !empty($data['status']) ? $data['status'] : 0;unset($data['status']);

        $update_state = GoodsModel::updatedData($data, $update_data);
        if (empty($update_state)) {
            throw new InvalidRequestException(30003);
        }

        return [];
    }

    /**
     * 获取 - 商品详情
     *
     * @param $data //请求参数数组
     * @return array
     */
    public static function getGoodsInfo($data)
    {
        if (!isset($data['goods_id']) && empty($data['goods_id'])) {
            throw new InvalidRequestException(30000);
        }

        $where_data[] = ['goods.id', '=', $data['goods_id']];
        $select = [
            'goods.id', 'goods.type', 'goods.title', 'goods.subtitle', 'goods.title_tag', 'goods.thumb_url',
            'goods.video_url', 'goods.thumb', 'goods.keywords', 'goods.categorys', 'goods.group', 'goods.is_support', 'goods.status',
            'goods.city', 'goods.province', 'goods.region', 'goods.city_id', 'goods.short_title', 'goods.tag_ids', 'goods.display_order',
            'goods.created_at', 'goods_cron_time.listing_time', 'goods_cron_time.off_shelf_time', 'goods_quota.quota_status', 'goods_quota.forerver_quota_status',
            'goods_quota.cycle_quota_status', 'goods_quota.cycle', 'goods_quota.customize_status', 'goods_quota.customize_day', 'goods_quota.customize_piece',
            'goods_quota.browse_right_status',
        ];
        $list = GoodsModel::detail_info($where_data, $select);
        if (empty($list)) {
            throw new InvalidRequestException(10009);
        }

        // 商品轮播图
        if (!empty($list->thumb_url)) {
            $list->thumb_url = get_string_array($list->thumb_url);
        }
        // 关键词
        if (!empty($list->keywords)) {
            $list->keywords = GoodsKeywordModel::in_arr($list->keywords);
        }
        // 商品分类
        if (!empty($list->categorys)) {
            $list->categorys = CategoryModel::in_arr($list->categorys);
        }
        // 商品分组
        if (!empty($list->group)) {
            $list->group = GoodsGroupModel::in_arr($list->group);
        }
        // 商品支持
        if (!empty($list->is_support)) {
            $list->is_support = GoodSupportModel::in_arr($list->is_support);
        }
        // 商品特征标签
        if (!empty($list->tag_ids)) {
            $list->tag_ids = GoodsTagModel::in_arr($list->tag_ids);
        }

        return $list;
    }

}
